package org.springside.examples.miniweb.web.dictionary;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.examples.miniweb.entity.dictionary.DictionaryClass;
import org.springside.examples.miniweb.service.ServiceException;
import org.springside.examples.miniweb.service.dictionary.DictionaryClassManager;
import org.springside.examples.miniweb.service.dictionary.DictionaryDetailManager;
import org.springside.examples.miniweb.web.CrudActionSupport;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;
import org.springside.modules.orm.hibernate.HibernateUtils;
import org.springside.modules.web.struts2.Struts2Utils;

@Namespace("/dictionary")
// http://localhost:8080/crm/dictionary/list.action
// 定义名为reload的result重定向到dictionaryClass.action, 其他result则按照convention默认.
@Results( { @Result(name = CrudActionSupport.RELOAD, location = "dictionary-class.action", type = "redirect") })
public class DictionaryClassAction extends CrudActionSupport<DictionaryClass> {

	private static final long serialVersionUID = 1L;

	@Autowired
	private DictionaryClassManager dictionaryClassManager;
	@Autowired
	private DictionaryDetailManager dictionaryDetailManager;

	// -- 页面元素--//
	private Long id;
	private DictionaryClass entity;
	private Page<DictionaryClass> page = new Page<DictionaryClass>(5);// 每页5条数�?

	private String datas;// format id@[0|1|2|3]@name,id@[0|1|2|3]@name....

	// -- ModelDriven与Preparable函数--//
	public void setId(Long id) {
		this.id = id;
	}

	public void setDatas(String datas) {
		this.datas = datas;
	}

	public DictionaryClass getModel() {
		return entity;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = dictionaryClassManager.getDictionaryClass(id);
		} else {
			entity = new DictionaryClass();
		}
	}

	// -- CRUD Action 函数 --//
	@Override
	public String list() throws Exception {
		List<PropertyFilter> filters = HibernateUtils.buildPropertyFilters(Struts2Utils.getRequest());
		// 设置默认排序方式
		if (!page.isOrderBySetted()) {
			page.setOrderBy("id");
			page.setOrder(Page.ASC);
		}
		page = dictionaryClassManager.searchDictionaryClass(page, filters);
		// page.setResult(dictionaryClassManager.getAllDictionaryClass());
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		return INPUT;
	}

	public String showList() throws Exception {
		entity = dictionaryClassManager.getDictionaryClass(id);
		ObjectMapper mapper = new ObjectMapper();
		ServletActionContext.getResponse().setContentType("text/json;charset=UTF-8");
//		mapper.writeValue(System.out, entity.getDictionaryDetails());
//		String result = mapper.writeValueAsString(entity.getDictionaryDetails());
//		result = "{\"id\":" + entity.getId() + ",\"name\":" + entity.getName() + ",\"dictionaryDetails\":" + result + "}";
//		System.out.println(result);
//		PrintWriter writer = ServletActionContext.getResponse().getWriter();
//		writer.write(result);
//		writer.flush();
//		writer.close();
		mapper.writeValue(ServletActionContext.getResponse().getWriter(), entity);
		return null;
	}

	public String updateAll() throws Exception {
		// datas id@[0|1|2|3]@name,id@[0|1|2|3]@name
		// 0 维持、1 新建、2 更新、3 删除
		try {
			if (StringUtils.isNotBlank(datas)) {
				String[] data = datas.split(",");
				for (String d : data) {
					String[] temp = d.split("@");
					if (temp.length != 3) {
						throw new RuntimeException("数据校验异常!");
					}
				}
				dictionaryDetailManager.updateAll(id, data);
			}
		} catch (Exception e) {
			logger.error("更新数据失败:" + datas);
			addActionMessage("更新数据失败，请刷新页面重试!");
		}
		return showList();
	}

	@Override
	public String save() throws Exception {
		dictionaryClassManager.saveDictionaryClass(entity);
		addActionMessage("保存成功");// TODO
		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		try {
			dictionaryClassManager.deleteDictionaryClass(id);
			addActionMessage("删除成功");
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionMessage("删除失败");
		}
		return RELOAD;
	}

	// -- 页面元素访问函数 --//
	/**
	 * list页面显示用户分页列表.
	 */
	public Page<DictionaryClass> getPage() {
		return page;
	}

}
